package github.sf.fw.tools.cmd;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import java.util.HashMap;
import java.util.Map;

public abstract class BaseCmd {
    protected final Map<String, CmdOption> nameAndOption = new HashMap<>();

    /**
     * 根据传入的参数，解析并生成命令
     *
     * @param param 传入的JSON参数
     * @return 生成的命令
     */
    public String build(JsonObject param) {
        StringBuilder cmdBuilder = new StringBuilder();
        cmdBuilder.append(getCommand()).append(CPC.BLANK.getSymbol());
        for (String paramName : param.keySet()) {
            CmdOption cmdOption = nameAndOption.get(paramName);
            JsonElement jsonElement = param.get(paramName);
            if (cmdOption != null && jsonElement.isJsonPrimitive()) {
                if (cmdOption.getCpc() != CPC.NONE && !jsonElement.isJsonNull()) {
                    cmdBuilder.append(cmdOption.getExpr())
                        .append(cmdOption.getParameterConnector())
                        .append(jsonElement.getAsString())
                        .append(CPC.BLANK.getSymbol());
                } else {
                    if (jsonElement.getAsJsonPrimitive().isBoolean()) {
                        boolean isUse = jsonElement.getAsBoolean();
                        if (!isUse) {
                            continue;
                        }
                    }
                    cmdBuilder.append(cmdOption.getExpr()).append(CPC.BLANK.getSymbol());
                }
            }
        }
        cmdBuilder.deleteCharAt(cmdBuilder.length() - 1);
        return cmdBuilder.toString();
    }

    public abstract String getCommand();
}
